<?php

namespace app\admin\controller\wx;

use app\common\controller\Backend;
use think\Config;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Wxproduct extends Backend
{
    
    /**
     * Wxproduct模型对象
     * @var \app\admin\model\Wxproduct
     */
    protected $model = null;
    protected $modelPro = null;
    protected $searchFields = 'name,id';
    protected $modelSceneValidate = true;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wxproduct;
        $this->modelPro = new \app\admin\model\Wxpro();
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("unitList", $this->model->getUnitList());
        $this->assignConfig("wxproIdsList", $this->model->getWxproidsList());
        //获取配置
        $config = Config::get('wxproduct');
        $config2 = Config::get('wxproduct2');
        $this->view->assign("wxProductType", !isset($config['type']) ? '':json_decode($config['type'],true));
        $this->view->assign("wxProductType2", !isset($config2['type']) ? '':json_decode($config2['type'],true));
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model

                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','code','type','name','ministrial','unit','kg','weigh','wxpro_ids']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 分类配置
     * @return string
     * @throws \think\Exception
     */
    public function config()
    {
        if($data = $this->request->post())
        {
            //设置配置
            if(!$this->model->setConfig($data['row'],'wxproduct'))
            {
                $this->error('保存失败！');
            }
            $this->success('修改成功');
        }
        //获取配置
        $config = Config::get('wxproduct');
        $this->view->assign('type',!isset($config['type']) ? '':$config['type']);
        return $this->view->fetch();
    }

    public function config2()
    {
        if($data = $this->request->post())
        {
            //设置配置
            if(!$this->model->setConfig($data['row'],'wxproduct2'))
            {
                $this->error('保存失败！');
            }
            $this->success('修改成功');
        }
        //获取配置
        $config = Config::get('wxproduct2');
        $this->view->assign('type',!isset($config['type']) ? '':$config['type']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(isset($params['wxpro_ids'])){
                $params['kg'] = number_format($this->modelPro->where('id','in',$params['wxpro_ids'])->sum('kg'),2);
                $params['ministrial'] = number_format($this->modelPro->where('id','in',$params['wxpro_ids'])->sum('ministrial'),2);
            }
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $validate = true;
                    if(!isset($params['name']))
                    {
                        $validate= false;
                    }
                    if(isset($params['name']) && $params['name'] == $row['name'])
                    {
                        $validate= false;
                    }
                    $result = $row->allowField(true)->validate($validate)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        if(!$error = $row->getError()) $error = '没有修改任何数据！';
                        $this->error($error);
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if ($row) {
                $nameArr = explode('+',$row['name']);
                $ids = [];
                $name = $nameArr[0];
                if(strpos($row['name'],'年级上下册年级阅读')){
                    foreach ($nameArr as $key=>$item1) {
                        if(strpos($item1,'四制五年级上下'))
                        {
                            $arr = ["五年级上年级阅读","五四制五年级下年级阅读"];
                        }elseif(strpos($item1,'三制五年级上下'))
                        {
                            $arr = ["五年级上年级阅读","六三制五年级下年级阅读"];
                        }else{
                            $nianji = substr($item1,0,3);
                            $arr = [$nianji."年级上年级阅读",$nianji."年级下年级阅读"];
                        }
                        foreach ($arr as $item)
                        {
                            if(!$row2 = $this->modelPro->get(['name'=>$item]))
                            {
                                $this->error('没找到半成品。'.$item."第{$currentRow}行");
                            }
                            $ids[] = $row2['id'];
                        }
                    }
                }elseif($row['type'] == 19){
                    $name = substr($row['name'], 0,15);
                    $arr = [
                        substr($row['name'], 15,12).$name,
                        substr($row['name'], 27,12).'人教版数学'
                    ];
                    unset($name);
                    foreach ($arr as $item)
                    {
                        if(!$row2 = $this->modelPro->get(['name'=>$item]))
                        {
                            $this->error('没找到半成品。'.$item."第{$currentRow}行");
                        }
                        $ids[] = $row2['id'];
                    }
                    $row['type'] = 18;
                } else{
                    unset($nameArr[0]);
                    foreach ($nameArr as $key => $item) {
                        $str = $name . $item;
                        if (strpos($str, '数学')) {
                            $str = substr($str, 9);
                        }
                        if (strpos($str, '字典')) {
                            $str = $name . '字词句手册';
                        }
                        if (strpos($str, '字词句手册')) {
                            $name = substr($name, 0, 9);
                            $str = $name . '字词句手册';
                        }
                        if (strpos($str, 'A')) {
                            $str = $name . 'A学习书';
                        }
                        if (strpos($str, 'B')) {
                            $str = $name . 'B练习书';
                        }
                        if (strpos($str, 'C')) {
                            $str = $name . 'C素材书';
                        }
                        if ($item == '年级阅读') {
                            $nianji = substr($name, 9, 18);
                            if($nianji == '五年级下')
                            {
                                $str = $name. '年级阅读';
                            }else{
                                $str = $nianji . '年级阅读';
                            }

                        }
                        if (!$row2 = $this->modelPro->get(['name' => $str])) {
                            $this->error('没找到半成品。' . $str . "第{$currentRow}行");
                        }
                        $ids[] = $row2['id'];
                    }
                }
                if(strpos($row['name'],'+A+B+C'))
                {
                    $row['name'] = str_replace('+A+B+C','ABC',$row['name']);
                }
                if(strpos($row['name'],'+A+B'))
                {
                    $row['name'] = str_replace('+A+B','AB',$row['name']);
                }
                $row['wxpro_ids'] = implode(',',$ids);
                $row['unit'] = 2;//套装
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll(array_filter($insert));
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if($params['wxpro_ids']){
                    $params['kg'] = number_format($this->modelPro->where('id','in',$params['wxpro_ids'])->sum('kg'),2);
                    $params['ministrial'] = number_format($this->modelPro->where('id','in',$params['wxpro_ids'])->sum('ministrial'),2);
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    if(isset($params['wxpro_ids'])) $params['kg'] = number_format($this->modelPro->where('id','in',$params['wxpro_ids'])->sum('kg'),2);
                    $result = $this->model->allowField(true)->validate(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function copy($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(isset($params['wxpro_ids']) && $params['wxpro_ids'])
            {
                if($kg =$this->modelPro->where('id',$params['wxpro_ids'])->sum('kg') != 0)
                {
                    $params['kg'] = $kg;
                }
            }else{
                $params['kg'] = $row['kg'];
            }
            $params['weigh'] = $row['weigh'];
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //新增数据
                    $result = $this->model->allowField(true)->validate(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $count = 0;
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save($values);
                }
                if ($count) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
        }
    }

    /**
     * 数据同步
     */
    public function copys($ids = null)
    {
        if(!$params = $this->request->request('params'))
        {
            $this->error('请输入“要替换”或“替换为”的内容。');
        }
        $params = explode(',',$params);
        $array = [];
        $list = collection($this->model->where("id",'in',$ids)->select())->toArray();
        foreach ($list as $item)
        {
            $item = array_filter($item);
            unset($item['id'],$item['type_text'],$item['unit_text'],$item['wxproids_text']);
            $item['name'] = str_replace($params[0],trim($params[1]?$params[1]:''),$item['name']);
            if(!$this->model->get(['name'=>$item['name']])) $array[] = $item;
        }
        $result = $this->model->saveAll($array);
        if ($result) {
            $count = count($array);
            $this->success("复制成功{$count}条");
        } else {
            $this->error(__('No rows were updated').'不能有重复的名称！');
        }
    }


    /**
     * 小学单科
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Cnm()
    {
        $list = $this->model->where('type','=',3)->select();
        $list =  collection($list)->toArray();
        foreach ($list as &$value)
        {
            $rowPro = $this->modelPro->get(['name'=>trim($value['wxproids_text']).'2020']);
            if($rowPro)
            {
                unset($value['type_text'],$value['unit_text'],$value['wxproids_text'],$value['id']);
                $value['wxpro_ids'] = $rowPro->id;
                $value['kg'] = $rowPro->kg;
                $value['name'] .= '2020';
                $item['updatetime'] = time();
            }else{
                $value = [];
            }
        }
        $this->AddProduct(array_filter($list));
    }

    public function AddProduct(array $list)
    {
        //添加一个新的成品
        Db::startTrans();
        try {
            $this->model->saveAll($list);
            // 提交事务
            Db::commit();
            echo "成功".count($list)."条";exit;
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage()."<br>";
            echo "<br> 有错误全部不添加";exit;
        }
    }

    public function Cnj()
    {
        $saveAll = [];
        $total = $this->model->where('type','=',18)->count();
        $limit = 100;
        $offset = ceil($total / $limit) ;
        for ($i=0;$i <= $offset;$i++)
        {
            $off = $limit * $i;
            $list = $this->model->where('type','=',18)->limit($off,$limit)->select();
            $list = collection((array)$list)->toArray();
            foreach ($list as &$item) {
                $akg = 0;
                $ids = [];
                $proName = array_filter(explode(',',$item['wxproids_text']));
                foreach ($proName as $vl)
                {
                    $rowPro = $this->modelPro->get(['name'=>$vl.'2020']);
                   if(!$rowPro)
                   {
                       echo "半成品错误<pre>".$vl.'2020';exit;
                   }
                    $akg += $rowPro->kg;
                    $ids[] = $rowPro->id;
                }
                $item['kg'] = $akg;
                $item['name'] .= '2020';
                $item['wxpro_ids'] = implode(',',$ids);
                $item['updatetime'] = time();
                unset($item['type_text'],$item['unit_text'],$item['wxproids_text'],$item['id']);
            }
            $saveAll = array_merge($saveAll,$list);
        }
        //添加一个新的成品
        $this->AddProduct($saveAll);
    }

    public function Upakg()
    {
        $total = $this->model->where('wxpro_ids','NOT NULL')->count();
        $limit = 100;
        $offset = ceil($total / $limit);
        $count = 0;
        for ($i=0;$i <= $offset;$i++)
        {
            $off = $limit * $i;
            $list = $this->model->where('wxpro_ids','NOT NULL')->limit($off,$limit)->select();
            foreach ($list as $value)
            {
                $sum = $this->modelPro->where('id','in',$value->wxpro_ids)->sum('kg');
                $ministrial = $this->modelPro->where('id','in',$value->wxpro_ids)->sum('ministrial');
                $value->kg = number_format($sum,2);
                $value->ministrial = $ministrial;
                $count += $value->isUpdate(true)->save();
            }
        }
        echo "成功".$count."条";exit;
    }

    public function zd($str)
    {
        ini_set('max_execution_time', 0);
        $count = $this->zidian($str);
        print_r($count);exit;
    }

    public function zidian($like)
    {
        $total = $this->model->where('type','=',18)->where('name','like','%'.$like.'%')->count();
        $limit = 100;
        $offset = ceil($total / $limit);
        $count = 0;
        for ($i=0;$i <= $offset;$i++) {
            $off = $limit * $i;
            $list = $this->model->where('type', '=', 18)->where('name','like','%'.$like.'%')->limit($off, $limit)->select();
            //判断是否六三   五四  判断是否2020
            foreach ($list as $value)
            {
                $name = substr($value['name'], 0,6);
                if ((!strpos($value['wxproids_text'], '字词句手册')) && $name == '五四') {
                    $value->wxpro_ids = $value->wxpro_ids.',688';
                    $count +=$value->save();
                }
                if ((!strpos($value['wxproids_text'], '字词句手册')) && $name == '六三') {
                    $value->wxpro_ids = $value->wxpro_ids.',784';
                    $count +=$value->save();
                }
            }
        }
        return $count;
    }

    public function config3()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $z = $params['xuezhi'];//学制
            $product = $params['product'];//产品
            $y = $params['y'];//年分
            $shi = $params['shi'];//是
            //获取1-6年级的年级阅读
            $list1 = $this->modelPro->where('name','like',$z.'一年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;
            $list2 = $this->modelPro->where('name','like',$z.'二年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;
            $list3 = $this->modelPro->where('name','like',$z.'三年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;
            $list4 = $this->modelPro->where('name','like',$z.'四年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;
            $list5 = $this->modelPro->where('name','like',$z.'五年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;
            $list6 = $this->modelPro->where('name','like',$z.'六年级%'.$product.$y)->field('group_concat('.$shi.') as cat_ids')->find()->cat_ids;

            $input=array($list1,$list2,$list3,$list4,$list5,$list6);
            $input2=array(
                $z.'一年级上下册'.$product.$y,
                $z.'二年级上下册'.$product.$y,
                $z.'三年级上下册'.$product.$y,
                $z.'四年级上下册'.$product.$y,
                $z.'五年级上下册'.$product.$y,
                $z.'六年级上下册'.$product.$y
            );
            $tong = [];
            foreach ($input as $yy)
            {
                $tong[] = [$yy,$yy];
            }
            $idstong = [];
            foreach ($input2 as $yy)
            {
                $idstong[] = [$yy,$yy];
            }
            $ids = $this->perm($input,2);
            $name = $this->perm($input2,2);
            $name = array_merge($name,$idstong);
            $ids = array_merge($ids,$tong);
            $arr = [];
            foreach ($name as $key=>$value)
            {
                if(isset($ids[$key][0]))
                {
                    $name1 = str_replace($z,'',$value[0]);
                    $name1 = str_replace($y,'',$name1);
                    $name2 = str_replace($z,'',$value[1]);
                    $name2 = str_replace($y,'',$name2);
                    $name3 = '';
                    if($params['weizhi'] == 1)
                    {
                        $name3 = $z.$name1.$name2;
                    }
                    if($params['weizhi'] == 2)
                    {
                        $name3 = $name1.$z.$name2;
                    }
                    if($params['weizhi'] == 3)
                    {
                        $name3 = $name1.$name2.$z;
                    }
                    if($y)
                    {
                        $name3 .= $y;
                    }
                    $idsName = $ids[$key][0].','.$ids[$key][1];
                    $str = explode(',',$idsName);
                    if (count($str) != count(array_unique($str)))
                    {
                        $str = explode(',',$ids[$key][1]);
                        foreach ($str as &$cp) {
                            $row = $this->modelPro->where($shi,$cp)->find();
                            if ($row['copy'] > 0) {
                                $row2 = $this->modelPro->get($row['copy']);
                                if ($shi == 'name') {
                                    $cp = $row2->name;
                                } else {
                                    $cp = $row2->id;
                                }
                            }else {
                                $data = $this->modelPro->insertGetId([
                                    'name'=>$row->name.'复',
                                    'code'=>$row->code,
                                    'kg'=>$row->kg,
                                    'weigh'=>$row->weigh,
                                    'type'=>$row->type,
                                    'fenlei'=>$row->fenlei,
                                    'kemu'=>$row->kemu,
                                    'banben'=>$row->banben,
                                    'ministrial'=>$row->ministrial,
                                ]);
                                $row->copy = $data;
                                $row->save();
                                if($shi =='name')
                                {
                                    $cp = $row->name.'复';
                                }else{
                                    $cp = $data;
                                }
                            }
                        }
                        $ids[$key][1] = $str;
                        $idsName = implode(',',$str).','.$ids[$key][0];
                    }
                    $arr[] = [
                        'name'=>$name3,
                        'ids'=>$idsName,
                    ];
                }
            }
            if($shi == 'name')
            {
                $html = "<table class='table table-striped table-bordered table-hover table-nowrap'>";
                $html .="<tr><th></th><th>序号</th><th></th><th>产品</th><th></th><th>产品详情</th></tr>";
                foreach ($arr as $key=>$value)
                {
                    $key +=1;
                    $html .="<tr>";
                    $html .="<th style=\"text-align: center; vertical-align: middle; \"><td style=\"text-align: center; vertical-align: middle; \">{$key}</td></th>";
                    $html .="<th style=\"text-align: center; vertical-align: middle; \"><td style=\"text-align: center; vertical-align: middle; \">{$value['name']}</td></th>";
                    $html .= "<th style=\"text-align: center; vertical-align: middle; \"><td style=\"text-align: center; vertical-align: middle; \">{$value['ids']}</td></th>";
                    $html .="</tr>";
                }
                $html .= "</table>";
                $this->error('','',$html);
            }else{
                foreach ($arr as &$value)
                {
                    $value['wxpro_ids'] = $value['ids'];
                    $value['type'] = 18;
                    $value['unit'] = 2;
                    unset($value['ids']);
                    if($value['wxpro_ids']){
                        $value['kg'] = number_format($this->modelPro->where('id','in',$value['wxpro_ids'])->sum('kg'),2);
                        $value['ministrial'] = number_format($this->modelPro->where('id','in',$value['wxpro_ids'])->sum('ministrial'),2);
                    }
                }
                Db::startTrans();
                try {
                    $this->model->saveAll($arr);
                    // 提交事务
                    Db::commit();
                    $this->success('操作成功！');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
        }
        //获取配置
        return $this->view->fetch();
    }

    //从$input数组中取$m个数的排列算法
    protected function perm($input,$m)
    {
        if($m==1)
        {
            foreach($input as $item)
            {
                $result[]=array($item);
            }
            return $result;
        }
        for($i=0;$i<count($input);$i++)
        {
            $nextinput=array_merge(array_slice($input,0,$i),array_slice($input,$i+1));
            $nextresult=$this->perm($nextinput,$m-1);
            foreach($nextresult as $one)
            {
                $result[]=array_merge(array($input[$i]),$one);
            }
        }
        return $result;
    }



}
